package com.jingjin.humanityservice.util.ranking;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jingjin.humanityservice.util.ranking.cacheData.CacheDataInRedis;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Component
public class DouyinRankingHandler {

    private static final HttpClient httpClient = HttpClient.newHttpClient();

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private CacheDataInRedis cacheDataInRedis;


    public Map<String, Object> handleRoute(Map<String, String> queryParams, boolean noCache) throws Exception {
        Map<String, Object> listResult = getList(noCache);

        Map<String, Object> routeData = new LinkedHashMap<>();
        routeData.put("name", "douyin");
        routeData.put("favicon", "https://www.douyin.com/favicon.ico");
        routeData.put("title", "抖音");
        Instant nowTime = Instant.now();
        // 将当前时间戳转换为上海时区
        ZonedDateTime Shanghai = nowTime.atZone(ZoneId.of("Asia/Shanghai"));
        routeData.put("nowTime", Shanghai);
        routeData.put("type", "热榜");
        routeData.put("link", "https://www.douyin.com/hot");
        routeData.put("total", ((List<?>) listResult.get("data")).size());

        List<Map<String, Object>> dataList = addIndexToDataList((List<Map<String, Object>>) listResult.get("data"));
        routeData.put("data", dataList);

        // 缓存数据到redis
        cacheDataInRedis.cacheData("douyin:hotSearch", routeData);

        return routeData;
    }

    private List<Map<String, Object>> addIndexToDataList(List<Map<String, Object>> dataList) {
        return IntStream.range(0, dataList.size())
                .mapToObj(index -> {
                    Map<String, Object> newItem = new LinkedHashMap<>();
                    newItem.put("index", index+1);
                    newItem.putAll(dataList.get(index));
                    return newItem;
                })
                .collect(Collectors.toList());
    }

    private String getDyCookies() throws Exception {
        String cookieUrl = "https://www.douyin.com/passport/general/login_guiding_strategy/?aid=6383";

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(cookieUrl))
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")
                .build();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        String setCookieHeader = response.headers().firstValue("set-cookie").orElse("");

        // Extract the csrf token from the set-cookie header
        String cookieData = extractCsrfToken(setCookieHeader);

        return cookieData;
    }

    private String extractCsrfToken(String setCookieHeader) {
        Pattern pattern = Pattern.compile("passport_csrf_token=(.*?);");
        Matcher matcher = pattern.matcher(setCookieHeader);
        if (matcher.find()) {
            return matcher.group(1);
        }
        throw new RuntimeException("CSRF token not found in set-cookie header");
    }

    private Map<String, Object> getList(boolean noCache) throws Exception {
        String cookie = getDyCookies();
        String url = "https://www.douyin.com/aweme/v1/web/hot/search/list/?device_platform=webapp&aid=6383&channel=channel_pc_web&detail_list=1";

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36")
                .header("Cookie", "passport_csrf_token=" + cookie)
                .build();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

        JsonNode resultNode = objectMapper.readTree(response.body());

        return parseResult(resultNode);
    }

    private Map<String, Object> parseResult(JsonNode resultNode) {
        JsonNode dataNode = resultNode.path("data");
        List<Map<String, Object>> list = objectMapper.convertValue(dataNode.path("word_list"), new TypeReference<List<Map<String, Object>>>() {});

        List<Map<String, Object>> mappedList = list.stream().map(v -> {
            Map<String, Object> item = new LinkedHashMap<>();
            item.put("title", v.get("word"));
            item.put("url", "https://www.douyin.com/hot/" + v.get("sentence_id"));
            item.put("mobileUrl", "https://www.douyin.com/hot/" + v.get("sentence_id"));
            return item;
        }).collect(Collectors.toList());

        Map<String, Object> result = new LinkedHashMap<>();
        result.put("fromCache", false);
        result.put("updateTime", System.currentTimeMillis());
        result.put("data", mappedList);

        return result;
    }

    public Map<String, Object> getRouteAndDataCombined(Map<String, String> queryParams, boolean noCache) throws Exception {
        return handleRoute(queryParams, noCache);
    }

    public Map<String, Object> getDouyinRanking() throws Exception {
        Map<String, String> queryParams = Collections.emptyMap();
        return getRouteAndDataCombined(queryParams, false);
    }
}
